<template>
  <div>
    <Spin size="large" fix v-if="spinShow"></Spin>
    <Row>
      <Col span="18">
      <Card>
        <Form ref="formGoods" :label-width="80">
          <FormItem label="商品名称">
            <Input v-model="goods.title" placeholder="名称"></Input>
          </FormItem>
          <FormItem label="商品描述">
            <Input v-model="goods.shortDesc" placeholder="描述"></Input>
          </FormItem>
          <!--<FormItem label="商品规格">-->
          <!--<i-switch size="large" v-model="goods.isSize">-->
          <!--<span slot="open">开启</span>-->
          <!--<span slot="close">关闭</span>-->
          <!--</i-switch>-->
          <!--</FormItem>-->
          <div class="size-open" v-if="goods.isSize">
            <FormItem label="定制规格">
              <Button type="success">添加规格</Button>
              <div class="margin-top-10">
                <FormItem v-for="(col, index1) in filterColumnList()" :key="index1">
                  <Input size="small" v-model="col.title" style="width: 50px"></Input>
                  <Tag v-for="(sub, index2) in col.subs" :key="index2" closable>{{sub.v}}</Tag>
                  <Button icon="ios-plus-empty" type="dashed" size="small"
                          @click="handleAddSize">添加标签
                  </Button>
                </FormItem>
              </div>

              <Card class="margin-top-10">
                <meditTable refs="goodsSize" v-model="editInlineAndCellData"
                            @on-cell-change="handleCellChange" @on-change="handleChange"
                            :editIncell="false" :columns-list="editInlineAndCellColumn">
                </meditTable>
              </Card>
            </FormItem>
          </div>
          <div class="size-close" v-else>
            <FormItem label="商品价格">
              <InputNumber v-model="goods.price" :min="1" style="width: 100%"></InputNumber>
            </FormItem>
            <FormItem label="商品数量">
              <InputNumber v-model="goods.count" :min="1" style="width: 100%"></InputNumber>
            </FormItem>
            <FormItem label="商品编码">
              <Input v-model="goods.code"></Input>
            </FormItem>
          </div>
          <FormItem label="图片组">
            <div class="demo-upload-list" v-for="item in defaultList">
              <template v-if="item.status === 'finished'">
                <img :src="item.url">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <Upload ref="upload" v-show="defaultList.length < 3" :show-upload-list="false"
                    :default-file-list="defaultList" :on-success="handleSuccess"
                    :max-size="2048" :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload"
                    multiple type="drag" action="http://localhost:8080/api/file/upload"
                    style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
            <Modal title="View Image" v-model="visible">
              <img :src="imageUrl" v-if="visible" style="width: 100%">
            </Modal>
          </FormItem>
        </Form>
        <div class="margin-top-20">
          <mtext v-model="goods.content" alse @on-ready="onEditorReady"
                 @on-destroy="onEditorDestroy" @on-upload-success="onEditorUploadComplete"
                 @on-upload-fail="onEditorUploadFail"></mtext>
        </div>
      </Card>
      </Col>
      <Col span="6" class="padding-left-10">
      <Card>
        <p slot="title">
          <Icon type="paper-airplane"></Icon>
          发布
        </p>
        <p class="margin-top-10">
          <Icon type="android-time"></Icon>&nbsp;&nbsp;状&nbsp;&nbsp;态&nbsp;
          {{checkOnSell(goods.onSell)}}
        </p>
        <Row class="margin-top-20 publish-button-con">
          <span class="publish-button">
            <Button @click="handleSaveDraft">保存草稿</Button>
          </span>
          <span class="publish-button">
            <Button @click="handlePublish" :loading="publishLoading"
                    icon="ios-checkmark" style="width:90px;" type="primary">上架</Button>
          </span>
        </Row>
      </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
  import meditTable from "components/meditTable";
  import mtext from "components/mtext";

  export default {
    components: {
      meditTable,
      mtext
    },
    data() {
      return {
        spinShow: false,
        goods: {
          id: '',
          title: '',
          poster: '',
          imageList: '',
          shortDesc: '',
          content: '',
          price: 0.0,
          count: 0,
          code: '',
          isSize: false,
          onSell: false
        },
        editInlineAndCellColumn: [
          {
            title: "颜色",
            align: "center",
            key: "color",
            subs: [
              {
                k: "r",
                v: "红色"
              },
              {
                k: "b",
                v: "蓝色"
              }
            ]
          },
          {
            title: "价格",
            align: "center",
            key: "price",
            editable: true
          },
          {
            title: "数量",
            align: "center",
            key: "count",
            editable: true
          },
          {
            title: "编码",
            align: "center",
            key: "code",
            editable: true
          },
          {
            title: "操作",
            align: "center",
            key: "handle",
            handle: ["edit"]
          }
        ],
        editInlineAndCellData: [
          {
            price: 100,
            count: 100,
            code: "Code01"
          },
          {
            price: 200,
            count: 200,
            code: "Code02"
          },
          {
            price: 300,
            count: 300,
            code: "Code03"
          }
        ],
        defaultList: [],
        publishLoading: false,
        imageUrl: "",
        visible: false
      };
    },
    mounted() {
      this.init();
    },
    methods: {
      filterColumnList() {
        var columnList = this.editInlineAndCellColumn;
        return columnList.filter((item, index) => {
          return index < columnList.length - 4;
        });
      },
      handleAddSize() {
      },
      init() {
        let id = this.$route.params.id;
        if (id !== 'add') {
          this.$axios({
            method: 'get',
            url: `/api/goods/${id}`,
          }).then((res) => {
            this.goods = res.data.result[0];
            console.log(this.goods);
            this.loadImages(this.goods.imageList);
          });
        }
      },
      loadImages(imageList) {
        let ids = imageList.split(',');
        console.log(ids);
        this.$axios({
          method: "post",
          url: '/api/image',
          data: {
            imageIds: ids,
          }
        }).then(res => {
          this.defaultList = res.data;
          this.defaultList.forEach(e => {
            e.name = e.id;
            e.url = e.imageBase;
            e.status = 'finished';
          });
        });
      },
      handleView(url) {
        this.imageUrl = url;
        this.visible = true;
      },
      handleRemove(file) {
        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      handleSuccess(res, file) {
        file.url = res.imageBase;
        file.name = res.id;
        file.id = res.id;
        file.status = "finished";
        this.defaultList.push(file);
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: "The file format is incorrect",
          desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: "Exceeding file size limit",
          desc: "File  " + file.name + " is too large, no more than 2M."
        });
      },
      handleBeforeUpload() {
        const check = this.defaultList.length < 3;
        if (!check) {
          this.$Notice.warning({
            title: "Up to five pictures can be uploaded."
          });
        }
        return check;
      },
      handleCellChange(val, index, key) {
        this.$Message.success(
          "修改了第 " + (index + 1) + " 行列名为 " + key + " 的数据"
        );
      },
      handleChange(val, index) {
        this.$Message.success("修改了第" + (index + 1) + "行数据");
      },
      checkOnSell(status) {
        if (status) return '已上架';
        else return '未上架'
      },
      onEditorReady() {
      },
      onEditorDestroy() {
      },
      onEditorUploadComplete([json, success, failure]) {
        success("http://localhost:8080/" + json.imagePath);
      },
      onEditorUploadFail() {
      },
      handleSaveDraft() {
        this.spinShow = true;
        let imageIds = [];
        this.defaultList.forEach(e => imageIds.push(e.id));
        this.goods.imageList = imageIds.join();
        this.$axios({
          method: 'post',
          url: '/api/goods/' + (this.goods.id ? this.goods.id : ''),
          data: {
            goods: this.goods
          }
        }).then((res) => {
          this.spinShow = false;
          if (res.data.status === 'success') {
            // console.log(res.data)
            this.$Notice.success({
              title: '保存成功!'
            });
            this.$router.push({
              path: `/admin/goods/${res.data.id}`,
            });
            // window.location.reload(true);
          } else {
            this.$Notice.error({
              title: '保存失败!'
            });
          }
        }).catch((error) => {
          this.spinShow = false;
          this.$Notice.error({
            title: '保存失败!'
          });
          console.log(error);
        });
      },
      handlePublish() {
        this.spinShow = true;
        this.publishLoading = true;
        this.$axios({
          method: 'put',
          url: `/api/goods/${this.goods.id}`,
          data: {
            onSell: '1'
          }
        }).then((res) => {
          this.spinShow = false;
          this.publishLoading = false;
          this.goods.onSell = true;
          this.$Notice.success({
            title: '上架成功!'
          });
        }).catch((error) => {
          this.spinShow = false;
          this.publishLoading = false;
          this.$Notice.error({
            title: '上架失败!'
          });
        })
      },
    }
  };
</script>
<style>
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
